package com.hk.servlet;

import com.hk.model.OnlineMessage;
import com.hk.service.IOnlineMessageService;
import com.hk.service.impl.OnlineMessageServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: KangWang
 * Date: 2021/5/17 10:20
 * State：Servlet 数据请求转发 控制层
 */
@WebServlet("/onlineMessage")
public class OnlineMessageServlet extends HttpServlet {

    IOnlineMessageService iOnlineMessageService = new OnlineMessageServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        设置UTF-8
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        获取项目路径
        String path = req.getServletContext().getRealPath("");
//        页面转发
        req.getRequestDispatcher("/jsp/online_message.jsp").forward(req,resp);
    }

//    模拟数据库设定ID自增
    int messageId = 1;
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        设置UTF-8
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");
//        获取项目路径
        String path = req.getServletContext().getRealPath("");
//        获取前端传递过来的数据
        String messageTitle = req.getParameter("messageTitle");
        String messageEmail = req.getParameter("messageEmail");
        String messageContent = req.getParameter("messageContent");
//        将获取到的数据进行封装
        OnlineMessage onlineMessage = new OnlineMessage(messageId++,messageTitle,messageEmail,messageContent);
        iOnlineMessageService.saveMessage(path,onlineMessage);
//      重定向页面
//        resp.sendRedirect("onlineMessage");
        //        页面转发
        req.getRequestDispatcher("/jsp/online_message.jsp").forward(req,resp);
    }
}
